<?php
/*
This php requires the following variables to be set correctly and is meant only for includes and not usable on its own.
   $readonly = bool -> controls wether the table entry can be edited
   $loc_entity = localised nice name for the table entity;
   $action = php to be called in action field of form(if $readonly is true). Requires the called php to handle $_GET["id"]
   Field definitions array
    name -> fieldname as in specified in sql
    loc -> localised nice name
    type -> Type of field (text, selection, number?)
    limit -> if type == text sets maxlength of input field
    readonly -> disallowes changing of specific field even if $readonly is false
    sql -> select for populating the selection type field(presumes name and retired fields within that table)
   example:
   $fields = [
    ["name" => "name", "loc" => "Name", "type" => "text", "limit" => 50],
    ["name" => "project_id", "loc" => "Projekt", "type" => "selection", "sql" => "SELECT * FROM project where retired is null"],
    ["name" => "created", "loc" => "Erstellt", "type" => "text", "readonly" => true],
   ];

   $row = row of edited Entity assumed to have the name parameters from fields
    $fallback = page to go back to in case of error
*/
$id = 0;
if($row != 0)
    $id = $row['id'];

?>


<html>

<head>
    <title>Easy Time Tracker</title>
    <link rel="stylesheet" href="/timetracker.css" type="text/css" media="screen" />
</head>

<body>
    <div align="center">
        <h3><?php printf (($readonly ? RLang("display_entity")  : RLang("edit_entity")), $loc_entity); ?></h3>
        <div class="BorderBox" align="center">
            <?php if (!$readonly)  printf("<form method='post' action='%s?id=%u' >", $action, $id); ?>
            <table>
                <?php
                if ($readonly && $row == 0) {
                    $_SESSION['msgtype'] = "msg";
                    $_SESSION['msg'] = sprintf(RLang("err_open_new_and_readonly"), $loc_entity);
                    header("location: $fallback");
                    exit();
                }
                foreach ($fields as $field) {
                    $loc_name = $field["loc"];
                    $name = $field["name"];
                    $type = $field["type"];
                    $limit = isset($field["limit"]) ? $field["limit"] : 0;
                    $sql = isset($field["sql"]) ? $field["sql"] : null;
                    $freadonly = isset($field["readonly"]) ? $field["readonly"] : false;
                    //When creating a new entity, readonly field can only be empty, so ignore them
                    if($freadonly && $row == 0)
                        continue;
                    //Print field Label
                    printf("<tr><td>%s</td><td>", $loc_name);
                    //Deal with readonly
                    if ($readonly || $freadonly)
                        echo ($row[$name]);
                    else {
                        //Determine field type and print input fields accordingly
                        if ($type == "text" || $type == "number") {
                            printf("<input type='%s' id='%s' name='%s' ", $type, $name, $name);
                            if ($limit > 0)
                                printf("maxlength='%u'", $limit);
                            if ($id != 0) printf("value='%s'", $row[$name]);
                            echo (">\r\n");
                        } else if ($type == "selection" && $sql != null) {
                            echo ("<select id='$name' name='$name'>\r\n");

                            if (!$result = get_db_result($db, $sql, null)) {
                                echo ($sql . " ");
                                die(mysqli_error($db));
                            }
                            $rowcnt = mysqli_num_rows($result);
                            //in case you try and create a new e.g. Task when there is no (active) Project.
                            if ($rowcnt == 0) {
                                $_SESSION['msgtype'] = "error";
                                $_SESSION['msg'] = sprintf(RLang("err_create_failed_no_possible_fk"),$loc_entity, $loc_name, $sql );
                                header("Location: $fallback");
                            }

                            $rowcnt = mysqli_num_rows($result);
                            for ($e = 0; $e < $rowcnt; $e++) {
                                $orow = mysqli_fetch_array($result, MYSQLI_ASSOC);
                                $oid = $orow['id'];
                                echo ("<option value='$oid' ");
                                if ($oid == $row[$name])
                                    echo ("selected");
                                printf(">%s</option>\r\n", $orow['name']);
                            }
                            echo ("</select>\r\n");
                        } else {
                            //Should never happen, if i tested right, but just in case...
                            printf ( RLang("err_unknown_type"), $name, $type);
                            print_r($field);
                        }
                    }
                    echo ("</td></tr>\r\n");
                }
                ?>

            </table>
            <?php if (!$readonly)  printf ("
            <button type='submit' value='%s' class='tooltip'><img src='icons/22/document-save.png'>
            <div class='rtooltiptext'>%0s</div>
            </button>", RLang("save"));
            ?>
            <a href='maintime.php' class='tooltip'><img src='icons/22/edit-undo.png'>
                <div class='rtooltiptext'><?php ELang("back"); ?></div>
            </a>
            <?php if (!$readonly)  echo ("</form>"); ?>
        </div>
    </div>
</body>

</html>